package cn.flaty.utils.web.file;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StopWatch;

import cn.flaty.utils.web.file.UploadInfo;
import cn.flaty.utils.web.file.UploadResult;

public class LocalFileUpload extends AbstractFileUpload{
	
	private static Logger log = LoggerFactory.getLogger(LocalFileUpload.class);

	@Override
	protected UploadResult writeFile(UploadInfo fileInfo) {
		UploadResult ur = null;
		ur = this.initBasicUploadResult(fileInfo);
		StopWatch  watch = new StopWatch();
		watch.start("上传文件");
		// 使用分段写入,防止内存溢出
		byte buffer[] = new byte[256 * 1024];
		File file = new File(FilenameUtils.normalize(fileInfo.getWebRootPath()
				+ ur.getWebLinkfileName()));
		InputStream in = null;
		OutputStream out = null;
		try {
			out = FileUtils.openOutputStream(file);
			in = fileInfo.getInputStream();
			// 写入文件
			while ((in.read(buffer)) != -1) {
				out.write(buffer);
			}
			in.close();
			out.close();
		} catch (IOException e) {
			ur.setSuccess(false);
			ur.setWebLinkfileName("");
			ur.setMessage("======>>文件上传失败!" + e.getMessage());
//			e.printStackTrace();
		}finally{
			fileInfo = null;
		}
		watch.stop();
		log.info(watch.prettyPrint());
		ur.setSuccess(true);
		return ur;
	}
	
	
	private UploadResult initBasicUploadResult(UploadInfo uploadInfo
			) {
		UploadResult ur = new UploadResult();
		ur.setRealFileName(uploadInfo.getOriginalFileName());
		ur.setUploadFormName(uploadInfo.getFormName());
		Date nowDay = new Date();
		String fileName = DigestUtils.md5Hex(nowDay.getTime() + "");
		String relativeWebRootPathFile = super.getRelativeUploadPath()
				+ File.separator
				+ DateFormatUtils.format(nowDay.getTime(), "yyyyMMdd")
				+ File.separator + (fileName + "." + ur.getFileExtName());
		ur.setWebLinkfileName(relativeWebRootPathFile);
		return ur;
	}

}
